package com.taptech.doufu.util;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Animatable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.controller.BaseControllerListener;
import com.facebook.drawee.controller.ControllerListener;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.common.ResizeOptions;
import com.facebook.imagepipeline.image.ImageInfo;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.taptech.doufu.sdk.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.taptech.doufu.sdk.universalimageloader.core.DisplayImageOptions;
import com.taptech.doufu.sdk.universalimageloader.core.ImageLoader;
import com.taptech.doufu.sdk.universalimageloader.core.ImageLoaderConfiguration;
import com.taptech.doufu.sdk.universalimageloader.core.assist.FailReason;
import com.taptech.doufu.sdk.universalimageloader.core.assist.ImageLoadingListener;
import com.taptech.doufu.sdk.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.taptech.doufu.sdk.qiniu.resumableio.PutExtra;
import com.taptech.doufu.sdk.qiniu.service.QiniuService;
import com.taptech.doufu.R;
import com.taptech.doufu.app.WeMediaApplication;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.listener.HttpResponseListener;
import com.taptech.doufu.listener.UploadImageListener;
import com.taptech.doufu.listener.UGCJSONObjectRet;
import com.taptech.doufu.services.UGCMainService;
import com.taptech.doufu.ui.view.WaitDialog;
import com.taptech.doufu.util.DiaobaoUtil.FileType;
import com.taptech.doufu.net.httputils.HttpResponseObject;
import com.taptech.doufu.net.httputils.NetworkImageResListener;
import com.taptech.doufu.ui.view.ImageUtil;
import com.taptech.doufu.ui.view.photoview.PhotoViewAttacher;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashSet;
import java.util.Set;

public class ImageManager {

    private static WeakMemoryCache caches = new WeakMemoryCache();
    private static ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(WeMediaApplication.applicationContext).threadPriority(Thread.NORM_PRIORITY - 1).denyCacheImageMultipleSizesInMemory().memoryCacheSize(1024).build();

    public static DisplayImageOptions defaultoptions = new DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisc(true).build();
    public static DisplayImageOptions bigPhotooptions = new DisplayImageOptions.Builder().showImageForEmptyUri(R.drawable.bg_home_photo_default).showImageOnFail(R.drawable.bg_home_photo_default).cacheInMemory(true).cacheOnDisc(true).bitmapConfig(Bitmap.Config.RGB_565).build();

    private static Set<String> myUrlSet = new HashSet<String>();
    ;

    public ImageManager() {
        if (!ImageLoader.getInstance().isInited()) {
            ImageLoader.getInstance().init(configuration);
        }
    }

    public static synchronized void displayImage(ImageView img,  String url) {
        url = Constant.changeUrlHost(url);
        if (TextUtils.isEmpty(url))
            return;
        GlideUtil.displayImage(img, url);
    }

    /**
     * @param img  控件
     * @param url  图片地址
     * @param type 加载默认图片
     */
    public static synchronized void displayImage(ImageView img, String url, int type) {
        url = Constant.changeUrlHost(url);
        if (TextUtils.isEmpty(url))
            return;
        GlideUtil.displayImage(img, url);
    }


    public static void displayImage(ImageView img, String url, NetworkImageResListener listener) {
        url = Constant.changeUrlHost(url);
        if (TextUtils.isEmpty(url))
            return;
        img.setTag(url);
        ImageLoader.getInstance().displayImage(url, img, defaultoptions, new DefualtLoadingListener(listener));
    }

    public static void displayImage(ImageView img, String url, DisplayImageOptions options, NetworkImageResListener listener) {
        if (TextUtils.isEmpty(url))
            return;
        url = Constant.changeUrlHost(url);
        img.setTag(url);
        ImageLoader.getInstance().displayImage(url, img, options, new DefualtLoadingListener(listener));
    }

    public static synchronized void displayImage(final ImageView img, String url, final int width, final int height) {
        if (TextUtils.isEmpty(url))
            return;
        url = Constant.changeUrlHost(url);
        img.setTag(url);
        ImageLoader.getInstance().displayImage(url, img, defaultoptions, new ScaleLoadingListener(img, width, height));
    }


    /**
     * 优化test
     */
    public static Bitmap getMemoryCacheBitMap(String url) {
        url = Constant.changeUrlHost(url);
        if (url == null)
            return null;
        Bitmap bitmap = null;
        try {
            bitmap = caches.get(url);
            if (bitmap == null || bitmap.isRecycled()) {
                bitmap = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return bitmap;

    }


    public static Bitmap getCacheBitMap(String url) {
        url = Constant.changeUrlHost(url);
        if (url == null)
            return null;
        Bitmap bitmap = null;
        try {
            bitmap = caches.get(url);
            if (bitmap == null || bitmap.isRecycled()) {
                int cachefile = url.hashCode();
                File file = new File(Constant.AppDir.DIR_CACHE_IMAGE + cachefile);
                if (file.exists()) {
                    bitmap = CacheUtil.readBitmapFromCache(file);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return bitmap;
    }

    public static String getCacheFilePath(String url) {
        try {
            String filePath = Constant.AppDir.DIR_CACHE_IMAGE + url.hashCode();
            File file = new File(filePath);
            if (file.exists()) {
                return filePath;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static void loadImage(SimpleDraweeView image, String icon, float v, final TextView title) {
        loadImage(image, icon, v, new BaseControllerListener<ImageInfo>() {
            @Override
            public void onSubmit(String id, Object callerContext) {
                super.onSubmit(id, callerContext);
            }

            @Override
            public void onFinalImageSet(String id, ImageInfo imageInfo, Animatable animatable) {
                super.onFinalImageSet(id, imageInfo, animatable);
                title.setVisibility(View.GONE);
            }

            @Override
            public void onRelease(String id) {
                super.onRelease(id);

            }
        });
    }

    static class DefualtLoadingListener implements ImageLoadingListener {

        NetworkImageResListener listener;

        public DefualtLoadingListener(NetworkImageResListener listener) {
            this.listener = listener;
        }

        @Override
        public void onLoadingStarted(String imageUri, View view) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onLoadingFailed(String imageUri, View view, FailReason failReason) {

        }

        @Override
        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
            this.listener.loadComplete(imageUri, view, loadedImage);
        }

        @Override
        public void onLoadingCancelled(String imageUri, View view) {

        }
    }

    public static class ScaleLoadingListener implements ImageLoadingListener {
        ImageView image;
        int imageWidth, imageHeight;

        public ScaleLoadingListener(ImageView image, int width, int height) {
            this.image = image;
            this.imageWidth = width;
            this.imageHeight = height;
        }

        @Override
        public void onLoadingStarted(String imageUri, View view) {

        }

        @Override
        public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
            image.post(new Runnable() {
                @Override
                public void run() {
                    UIUtil.dismissDialog();
                    UIUtil.toastMessage(image.getContext(), "Oops，很抱歉图碎了，请重新加载");
                }
            });
        }

        @Override
        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
            if (imageWidth == 0) {
                loadedImage = scaleImage(image, loadedImage);
                image.setImageBitmap(loadedImage);
                image.setVisibility(View.VISIBLE);
            } else {
                Bitmap newBitmap;
                newBitmap = ImageUtil.cutImage(loadedImage, imageWidth, imageHeight);
                if (image.getWidth() == 0 || image.getHeight() == 0) {
                    image.getLayoutParams().width = newBitmap.getWidth();
                    image.getLayoutParams().height = newBitmap.getHeight();
                }
                image.setImageBitmap(newBitmap);
                image.setVisibility(View.VISIBLE);
            }

            image.post(new Runnable() {

                @Override
                public void run() {
                    UIUtil.dismissDialog();
                }
            });
        }

        @Override
        public void onLoadingCancelled(String imageUri, View view) {

        }

    }

    public static Bitmap scaleImage(ImageView image, Bitmap loadedImage) {

        try {
            float scale = (float) ScreenUtil2.SCREEN_PX_WIDTH / (float) loadedImage.getWidth();

            if (scale < 1) {
                image.getLayoutParams().width = ScreenUtil2.SCREEN_PX_WIDTH;
                image.getLayoutParams().height = (int) (scale * loadedImage.getHeight());
            } else {

                if (loadedImage.getHeight() > 4096) {
                    scale = 4096f / loadedImage.getHeight();
                    int dstWidth = (int) (loadedImage.getWidth() * scale);
                    loadedImage = Bitmap.createScaledBitmap(loadedImage, dstWidth, 4096, false);

                }
                image.getLayoutParams().width = loadedImage.getWidth();
                image.getLayoutParams().height = loadedImage.getHeight();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return loadedImage;


    }

    public static void uploadImage(String path, UploadImageListener listener) {
        path = Constant.changeUrlHost(path);
        byte[] data = ImageUtil.getimageToByte(path);
        upload(data, listener);
    }


    private static void upload(final byte[] data, final UploadImageListener listener) {
        if (data == null) {
            listener.onPath("");
            return;
        }
        uploadImage(data, new UGCJSONObjectRet() {
            @Override
            public void onFailure(Exception ex) {
                ex.printStackTrace();
                listener.onPath("");
            }

            @Override
            public void onPause(Object tag) {
                TTLog.s("onPause===========");
            }

            @Override
            public void onSuccess() {
                TTLog.s("onSuccess===========");
                if (data == null) {
                    return;
                }
                String hashValue = FileHashUtil.getDiabaoFileSHA384(data, FileType.PNG, "diaobaoimg/comment/");
                String url = Constant.DIAOBAO_IMAGE_HOST + hashValue;
                listener.onPath(url);
            }

            @Override
            public void onFailure() {
                listener.onPath("");
            }
        });
    }


    /**
     * 单张图片上传到七牛服务器
     * mContext
     * ret
     */
    private static void uploadImage(final byte[] data, final UGCJSONObjectRet listener) {
        UGCMainService.getInstance().getQiniuToken(new HttpResponseListener() {
            @Override
            public void handleResponse(int handleType, HttpResponseObject response) {
                if (response.getStatus() == 0) {
                    try {
                        JSONObject obj = (JSONObject) response.getData();
                        JSONObject result = obj.getJSONObject(Constant.RESULT);
                        QiniuService.QINIU_TOKEN = obj.getString(QiniuService.TOKEN);
                        PutExtra mExtra = new PutExtra();
                        String hashValue = FileHashUtil.getDiabaoFileSHA384(data, FileType.PNG, "diaobaoimg/comment/");
                        if (result.has(hashValue) && result.getInt(hashValue) == 1) {
                            listener.onSuccess();
                        } else {
                            UGCMainService.getInstance().uploadQiniu(hashValue, data, mExtra, listener);
                        }
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                } else {
                    listener.onFailure();
                }
            }
        }, data);
    }


    /**
     * bitmap单张图片上传到七牛服务器
     * mContext
     * ret
     */
    public static void uploadImage(final Bitmap bitmap, final UGCJSONObjectRet ret) {
        UGCMainService.getInstance().getQiniuToken(new HttpResponseListener() {
            @Override
            public void handleResponse(int handleType, HttpResponseObject response) {
                // TODO Auto-generated method stub
                if (response.getStatus() == 0) {
                    try {
                        JSONObject obj = (JSONObject) response.getData();
                        JSONObject result = obj.getJSONObject(Constant.RESULT);
                        QiniuService.QINIU_TOKEN = obj.getString(QiniuService.TOKEN);
                        PutExtra mExtra = new PutExtra();
                        byte[] datas = ImageUtil.Bitmap2Bytes(bitmap);
                        String hashValue = FileHashUtil.getDiabaoFileSHA384(datas, FileType.PNG);
                        if (result.has(hashValue) && result.getInt(hashValue) == 1) {
                            ret.onSuccess();
                        } else {
                            UGCMainService.getInstance().uploadQiniu(hashValue, datas, mExtra, ret);
                        }
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }


                } else {
                }
            }
        }, bitmap);

    }


    public static void selectPhotoDialog(final Context mContext, String title) {
        new AlertDialog.Builder(mContext).setTitle(title).setNegativeButton("相册", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                /**
                 * 刚开始，我自己也不知道ACTION_PICK是干嘛的，后来直接看Intent源码，
                 * 可以发现里面很多东西，Intent是个很强大的东西，大家一定仔细阅读下
                 */
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                /**
                 * 下面这句话，与其它方式写是一样的效果，如果：
                 * intent.setData(MediaStore.Images
                 * .Media.EXTERNAL_CONTENT_URI);
                 * intent.setType(""image/*");设置数据类型
                 * 如果朋友们要限制上传到服务器的图片类型时可以直接写如
                 * ："image/jpeg 、 image/png等的类型"
                 * 这个地方小马有个疑问，希望高手解答下：就是这个数据URI与类型为什么要分两种形式来写呀?有什么区别?
                 */
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                ((Activity) mContext).startActivityForResult(intent, 1);
            }
        }).setPositiveButton("拍照", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                dialog.dismiss();
                /**
                 * 下面这句还是老样子，调用快速拍照功能，至于为什么叫快速拍照，大家可以参考如下官方
                 * 文档，you_sdk_path/docs/guide/topics/media/camera.html
                 * 我刚看的时候因为太长就认真看，其实是错的，这个里面有用的太多了，所以大家不要认为
                 * 官方文档太长了就不看了，其实是错的，这个地方小马也错了，必须改正
                 */
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                // 下面这句指定调用相机拍照后的照片存储的路径
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "xiaoma.jpg")));
                ((Activity) mContext).startActivityForResult(intent, 2);
            }
        }).show();
    }


    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    public static void startPhotoZoom(Uri uri, Context mContext, int width, int height) {
        /*
         * 至于下面这个Intent的ACTION是怎么知道的，大家可以看下自己路径下的如下网页
         * yourself_sdk_path/docs/reference/android/content/Intent.html
         * 直接在里面Ctrl+F搜：CROP ，之前小马没仔细看过，其实安卓系统早已经有自带图片裁剪功能, 是直接调本地库的，小马不懂C C++
         * 这个不做详细了解去了，有轮子就用轮子，不再研究轮子是怎么 制做的了...吼吼
         */
        Intent intent = new Intent("com.android.camera.action.CROP");
        //需要加上这两句话  ： uri 权限
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        intent.setDataAndType(uri, "image/*");
        // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        intent.putExtra("scale", true);//去黑边
        intent.putExtra("scaleUpIfNeeded", true);//去黑边
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", width);
        intent.putExtra("aspectY", height);
        // outputX outputY 是裁剪图片宽高
//        intent.putExtra("outputX", width);
//        intent.putExtra("outputY", height);
        intent.putExtra("return-data", false);
        intent.putExtra("noFaceDetection", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getCutpicFile()));
        //		intent.putExtra("scale", false);
        ((Activity) mContext).startActivityForResult(intent, 3);
    }

    private static File getCutpicFile() {
        File f = new File(Environment.getExternalStorageDirectory() + "/Doufu/", "cutpic.jpg");
        try {
            f.createNewFile();
        } catch (IOException e) {

        }
        return f;
    }


    /**
     * 保存裁剪之后的图片数据
     * <p/>
     * picdata
     */
    public static Bitmap setPicToView(Bitmap bitmap, UGCJSONObjectRet ret) {
        if (bitmap == null)
            return bitmap;
        ImageManager.uploadImage(bitmap, ret);

        return bitmap;
    }


    public synchronized static void displayImageToFullWidth(ImageView imageView, final String url, final Handler handler) {

        String str = "http://imgold2.doufu.douhuayuedu.com/";
        final String urlHead = Constant.changeUrlHost(str);
        final ImageView imgView = imageView;
        final PhotoViewAttacher photoViewAttacher;
        if (imageView == null || url == null) {
            return;
        }
        imgView.setTag(url);
        if (myUrlSet == null || myUrlSet.contains(urlHead + url)) {

            return;
        }
        if (caches.get(urlHead + url) == null) {
            if (isBitmapExist(urlHead + url)) {
                Bitmap bm = loadBitmapFromFile(urlHead + url);
                imageView.setImageBitmap(bm);
                photoViewAttacher = new PhotoViewAttacher(imgView);
                photoViewAttacher.setmHandler(handler);
                if (bm == null) {
                    return;
                }
                int width = Integer.valueOf(bm.getWidth());
                int height = Integer.valueOf(bm.getHeight());
                if (width < height) {
                    photoViewAttacher.setScaleType(ImageView.ScaleType.MATRIX);
                }
                return;
            }
            myUrlSet.add(urlHead + url);

            ImageLoader.getInstance().loadImage(urlHead + url, ImageManager.bigPhotooptions, new SimpleImageLoadingListener() {
                @Override

                public void onLoadingComplete(String imageUri, View view, Bitmap bitmap) {

                    if (myUrlSet != null) {
                        myUrlSet.remove(urlHead + url);
                    }
                    if (imgView != null && bitmap != null) {
                        int width = Integer.valueOf(bitmap.getWidth());
                        int height = Integer.valueOf(bitmap.getHeight());
                        float bitmapScale = ScreenUtil2.SCREEN_PX_WIDTH / (float) (width);
                        int targetWidth = (int) (width * bitmapScale);
                        int targetHeight = (int) (height * bitmapScale);
                        Bitmap bm = Bitmap.createScaledBitmap(bitmap, targetWidth, targetHeight, true);

                        imgView.setLayerType(View.LAYER_TYPE_NONE, null);
                        if (bm != null) {
                            caches.put(urlHead + url, bm);
                            if (!isBitmapExist(urlHead + url)) {
                                saveBitmapToFile(bm, urlHead + url);
                            }
                        }
                        if (imgView.getTag() != null) {
                            String tempUrlString = urlHead + imgView.getTag().toString();

                            if (tempUrlString.equals(imageUri)) {
                                imgView.setImageBitmap(bm);

                                PhotoViewAttacher photoViewAttacher = new PhotoViewAttacher(imgView);
                                if (width < height) {
                                    photoViewAttacher.setScaleType(ImageView.ScaleType.MATRIX);
                                }

                                photoViewAttacher.setmHandler(handler);

                            } else {
                                ImageManager.displayImageToFullWidth(imgView, url, handler);
                            }

                        } else {
                            imgView.setImageBitmap(bm);

                        }
                    }
                }

                @Override
                public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                    super.onLoadingFailed(imageUri, view, failReason);

                    if (myUrlSet != null) {
                        myUrlSet.remove(urlHead + url);
                    }

                    TTLog.d("tag", "display the img failed========================" + url);
                }
            });
        } else {
            try {
                imgView.setImageBitmap(caches.get(urlHead + url));
                photoViewAttacher = new PhotoViewAttacher(imgView);
                photoViewAttacher.setmHandler(handler);
                int width = Integer.valueOf(caches.get(urlHead + url).getWidth());
                int height = Integer.valueOf(caches.get(urlHead + url).getHeight());
                if (width < height) {
                    photoViewAttacher.setScaleType(ImageView.ScaleType.MATRIX);
                }

                TTLog.d("tag", "display the img get in the cache======================" + url);
            } catch (Exception e) {
                TTLog.d("tag", "display the img start downLoading again========================" + url);

                ImageManager.displayImageToFullWidth(imgView, imgView.getTag().toString(), handler);

            }
        }
    }


    //图片缓存目录
    private static final String IMGCACHDIR = Constant.AppDir.DIR_CACHE_IMAGE;

    //保存的cache文件宽展名
    private static final String CACHETAIL = ".cach";


    private static void saveBitmapToFile(Bitmap bitmap, String url) {
        url = Constant.changeUrlHost(url);
        if (bitmap == null) {
            return;
        }
        File dirFile = new File(IMGCACHDIR);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        File file = new File(IMGCACHDIR + "/" + urlConvertToPath(url));
        try {
            file.createNewFile();
            OutputStream outputStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private static Bitmap loadBitmapFromFile(String url) {
        try {
            url = Constant.changeUrlHost(url);
            if (url != null) {
                final String path = IMGCACHDIR + "/" + urlConvertToPath(url);
                File file = new File(path);
                if (file != null && file.exists()) {
                    Bitmap bm = BitmapFactory.decodeFile(path);
                    if (bm == null) {
                        file.delete();
                    } else {
                        return bm;
                    }
                }
            }

        } catch (OutOfMemoryError e) {
        }


        return null;
    }

    private static boolean isBitmapExist(String url) {
        if (url != null) {
            final String path = IMGCACHDIR + "/" + urlConvertToPath(url);
            File file = new File(path);
            if (file != null && file.exists()) {
                return true;
            }
        }
        return false;
    }


    private static String urlConvertToPath(String url) {
        String path = "";
        path = url.hashCode() + CACHETAIL;
        return path;
    }

    /*--------------------------------------- Fresco加载方法 --------------------------------------*/

    /**
     * 加载图片,宽高取决于draweeView
     *
     * @param draweeView
     * @param imageUrl
     */
    static public void loadImage(SimpleDraweeView draweeView, String imageUrl) {
        imageUrl = Constant.changeUrlHost(imageUrl);
        Uri imgUri = Uri.parse(imageUrl);
        draweeView.setImageURI(imgUri);
    }

    /**
     * 加载图片
     *
     * @param imageAspectRatio                图片宽高比 宽/高
     * @param draweeView
     * @param imageUrl
     * @param imageInfoBaseControllerListener
     */
    static public void loadImage(SimpleDraweeView draweeView, String imageUrl, float imageAspectRatio, BaseControllerListener<ImageInfo> imageInfoBaseControllerListener) {
        imageUrl = Constant.changeUrlHost(imageUrl);
        Uri imgUri = Uri.parse(imageUrl);

        DraweeController controller = Fresco.newDraweeControllerBuilder().setImageRequest(ImageRequest.fromUri(imgUri)).setControllerListener(imageInfoBaseControllerListener).setOldController(draweeView.getController()).build();
        draweeView.setAspectRatio(imageAspectRatio);
        draweeView.setController(controller);
    }

    /**
     * 加载图片
     *
     * @param draweeView
     * @param imageUrl
     * @param imgWidth   图片宽度
     * @param imgHeight  图片高度
     */
    static public void loadImage(SimpleDraweeView draweeView, String imageUrl, int imgWidth, int imgHeight) {
        imageUrl = Constant.changeUrlHost(imageUrl);

        Uri imgUri = Uri.parse(imageUrl);
        int width = imgWidth, height = imgHeight;
        ImageRequest request = ImageRequestBuilder.newBuilderWithSource(imgUri).setResizeOptions(new ResizeOptions(width, height)).build();
        DraweeController controller = Fresco.newDraweeControllerBuilder().setOldController(draweeView.getController()).setImageRequest(request).build();
        draweeView.setController(controller);

    }


    static public void loadImage(SimpleDraweeView draweeView, String imageUrl, float imageAspectRatio) {
        imageUrl = Constant.changeUrlHost(imageUrl);
        Uri imgUri = Uri.parse(imageUrl);
        draweeView.setAspectRatio(imageAspectRatio);
        draweeView.setImageURI(imgUri);
    }

    /**
     * 加载图片
     *
     * @param draweeView
     * @param imageUrl
     * @param lowImageUrl       低质量图片url
     * @param imageAspetctRatio
     */
    static public void loadImage(SimpleDraweeView draweeView, String imageUrl, String lowImageUrl, float imageAspetctRatio) {
        imageUrl = Constant.changeUrlHost(imageUrl);
        if (lowImageUrl != null) {
            Uri imgUri = Uri.parse(imageUrl);
            Uri lowImgUri = Uri.parse(lowImageUrl);
            DraweeController controller = Fresco.newDraweeControllerBuilder().setLowResImageRequest(ImageRequest.fromUri(lowImgUri)).setImageRequest(ImageRequest.fromUri(imgUri)).setOldController(draweeView.getController()).build();
            draweeView.setAspectRatio(imageAspetctRatio);
            draweeView.setController(controller);
        } else {
            loadImage(draweeView, imageUrl, imageAspetctRatio);
        }

    }

    /**
     * 加载图片
     *
     * @param draweeView
     * @param imageUrl
     * @param lowImageUrl
     * @param imgWidth
     * @param imgHeight
     */
    static public void loadImage(SimpleDraweeView draweeView, String imageUrl, String lowImageUrl, int imgWidth, int imgHeight) {
        imageUrl = Constant.changeUrlHost(imageUrl);
        Uri imgUri = Uri.parse(imageUrl);
        Uri lowImgUri = Uri.parse(lowImageUrl);
        DraweeController controller = Fresco.newDraweeControllerBuilder().setLowResImageRequest(ImageRequest.fromUri(lowImgUri)).setImageRequest(ImageRequest.fromUri(imgUri)).setOldController(draweeView.getController()).build();
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(imgWidth, ViewGroup.LayoutParams.WRAP_CONTENT);
        draweeView.setLayoutParams(params);
        float imageAspetctRatio = imgWidth / (float) imgHeight;
        draweeView.setAspectRatio(imageAspetctRatio);
        draweeView.setController(controller);
    }

    /**
     * @param draweeView
     * @param imageUrl
     * @param lowImageUrl
     * @param imgWidth
     * @param imgHeight
     * @param controllerListener 图片加载完成的监听
     */
    static public void loadImage(SimpleDraweeView draweeView, String imageUrl, String lowImageUrl, int imgWidth, int imgHeight, ControllerListener controllerListener) {
        imageUrl = Constant.changeUrlHost(imageUrl);
        Uri imgUri = Uri.parse(imageUrl);
        Uri lowImgUri = Uri.parse(lowImageUrl);
        DraweeController controller = Fresco.newDraweeControllerBuilder().setLowResImageRequest(ImageRequest.fromUri(lowImgUri)).setImageRequest(ImageRequest.fromUri(imgUri)).setControllerListener(controllerListener).setOldController(draweeView.getController()).build();
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(imgWidth, ViewGroup.LayoutParams.WRAP_CONTENT);
        draweeView.setLayoutParams(params);
        float imageAspetctRatio = imgWidth / (float) imgHeight;
        draweeView.setAspectRatio(imageAspetctRatio);
        draweeView.setController(controller);
    }

    /**
     * @param draweeView
     * @param imageUrl
     * @param lowImageUrl
     * @param imageAspectRatio
     * @param imageInfoBaseControllerListener
     */
    static public void loadImage(SimpleDraweeView draweeView, String imageUrl, String lowImageUrl, float imageAspectRatio, BaseControllerListener<ImageInfo> imageInfoBaseControllerListener) {
        imageUrl = Constant.changeUrlHost(imageUrl);
        lowImageUrl = Constant.changeUrlHost(lowImageUrl);
        if (lowImageUrl != null) {
            Uri imgUri = Uri.parse(imageUrl);
            Uri lowImgUri = Uri.parse(lowImageUrl);
            DraweeController controller = Fresco.newDraweeControllerBuilder().setLowResImageRequest(ImageRequest.fromUri(lowImgUri)).setImageRequest(ImageRequest.fromUri(imgUri)).setControllerListener(imageInfoBaseControllerListener).setOldController(draweeView.getController()).build();
            draweeView.setAspectRatio(imageAspectRatio);
            draweeView.setController(controller);
        } else {
            loadImage(draweeView, imageUrl, imageAspectRatio, imageInfoBaseControllerListener);
        }
    }

    static public void loadGifImage(SimpleDraweeView draweeView, String imageUrl, float imageAspectRatio, BaseControllerListener<ImageInfo> baseControllerListener) {

        imageUrl = Constant.changeUrlHost(imageUrl);
        Uri uri = Uri.parse(imageUrl);
        ImageRequest request = ImageRequest.fromUri(uri);
        DraweeController controller = Fresco.newDraweeControllerBuilder().setImageRequest(request).setAutoPlayAnimations(true).build();
        draweeView.setAspectRatio(imageAspectRatio);
        draweeView.setController(controller);

    }

    /**
     * 通过Uri获取图片路径
     *
     * @param context
     * @param uri
     * @return
     */
    public static String getPath(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }

                // TODO handle non-primary volumes
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{
                        split[1]
                };

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {

            // Return the remote address
            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();

            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context       The context.
     * @param uri           The Uri to query.
     * @param selection     (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

}




